package org.easyspec.application

class CommandLineParser {

    private static def booleanFlagPattern = '^-([^-].*)$'
    private static def valueFlagPattern = '^--(.*)$'

    /**
     * Wants commandline arguments in flag, value pairs
     */
    public Map parse(args) {
        HashMap map = new HashMap()
        def i = 0
        while(i < args.size()) {
            def arg = args[i]
            if (isValueFlag(arg)) {
                i = processValueFlag(map, args, i)
            } else if (isBooleanFlag(arg)) {
                i = processBooleanFlag(map, args, i)
            } else {
                throw new RuntimeException("Not sure what to do with the commandline option '$arg'.  Check your syntax.")
            }
        }
        return map
    }

    def processValueFlag(map, args, i) {
        if (i+1 >= args.size()) {
            def arg = args[i]
            throw new RuntimeException("Cannot find a value to match with $arg")
        }
        def matcher = args[i] =~ valueFlagPattern
        def flag = matcher[0][1]
        map[flag] = args[i+1]
        return i + 2
    }

    def processBooleanFlag(map, args, i) {
        def matcher = args[i] =~ booleanFlagPattern
        def flag = matcher[0][1]
        map[flag] = true
        return i + 1
    }

    def isBooleanFlag(arg) {
        return arg =~ booleanFlagPattern
    }

    def isValueFlag(arg) {
        return arg =~ valueFlagPattern
    }

}